package com.ihk.toiletfinder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ihk.model.SearchGeoCoder;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

@SuppressLint({ "ParserError", "ParserError" })
public class SearchActivity extends Activity implements OnItemClickListener {
	
	/** Called when the activity is first created. */
	public ArrayAdapter<String> adapter;
	public AutoCompleteTextView textView;
	public static SearchGeoCoder geoCoder;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        
        geoCoder = new SearchGeoCoder();
        
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item);
        textView = (AutoCompleteTextView)
        findViewById(R.id.autoCompleteTextView1);
        adapter.setNotifyOnChange(true);
        textView.setAdapter(adapter);
        textView.setOnItemClickListener(this);

        textView.addTextChangedListener(new TextWatcher() {

        	public void onTextChanged(CharSequence s, int start, int before, int count) {
        		if (count%3 == 1) 
        		{
        				adapter.clear();
    		            GetPlaces task = new GetPlaces();
    		            //now pass the argument in the textview to the task
    		            task.execute(textView.getText().toString());
        		}
    		}

        	public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

        	public void afterTextChanged(Editable s) { }
        	
        });
	}
       
	/**
	 * Class to access places.
	 * TODO: Put it into a own file. Bit dirty in here.
	 */
	@SuppressLint({ "ParserError", "ParserError" })
	class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {

		@Override
        
		// three dots is java for an array of strings
		protected ArrayList<String> doInBackground(String... args) {

			Log.d("gottaGo", "doInBackground");

			ArrayList<String> predictionsArr = new ArrayList<String>();

			try
			{

	            URL googlePlaces = new URL(
	            // URLEncoder.encode(url,"UTF-8");
	                    "https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ URLEncoder.encode(args[0].toString(), "UTF-8") +"&types=geocode&language=en&sensor=true&key=AIzaSyCIzXByMktOE8ox_4F3Nqti8bGsFQTYrZg");
	            URLConnection tc = googlePlaces.openConnection();
	            BufferedReader in = new BufferedReader(new InputStreamReader(
	                    tc.getInputStream()));
	
	            String line;
	            StringBuffer sb = new StringBuffer();
	            
	            //take Google's legible JSON and turn it into one big string.
	            while ((line = in.readLine()) != null) 
	            {
	            	
	            	/**
	            	 * Shows the JSON output from Google
	            	 */
//	            	System.out.println(line);
	            	
	            	sb.append(line);
	            	
	            }
	            
	            //turn that string into a JSON object
	            JSONObject predictions = new JSONObject(sb.toString());
	            
	            //now get the JSON array that's inside that object           
	            JSONArray ja = new JSONArray(predictions.getString("predictions"));
	
                for (int i = 0; i < ja.length(); i++) 
                {
                    JSONObject jo = (JSONObject) ja.get(i);
                    
                    //add each entry to our array
                    predictionsArr.add(jo.getString("description"));
                    
                }
			} 
			catch (IOException e) {
				Log.e("ToiletFinder", "GetPlaces : doInBackground", e);
			} 
			catch (JSONException e)	{
				Log.e("ToiletFinder", "GetPlaces : doInBackground", e);
			}

			return predictionsArr;
		}
		
		/**
		 * PostExecute
		 */
		protected void onPostExecute(ArrayList<String> result) {
		
			Log.d("ToiletFinder", "onPostExecute : " + result.size());
			
			//update the adapter
			adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.list_item);
			adapter.setNotifyOnChange(true);
			
			//attach the adapter to textview
			textView.setAdapter(adapter);
			
			for (String string : result)
			{
				
				Log.d("ToiletFinder", "onPostExecute : result = " + string);
				adapter.add(string);
				adapter.notifyDataSetChanged();
			
			}
			
			Log.d("ToiletFinder", "onPostExecute : autoCompleteAdapter" + adapter.getCount());
		
		}
	}
		
	/**
	 * Access the clicked listItem
	 */
	@SuppressLint("ParserError")
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		
        String str = (String) adapterView.getItemAtPosition(position);
        
        Log.d("ToiletFinder", "LocationTitle : result = " + str);

        try {
			SearchGeoCoder.getLocation(str);
		} catch (IOException e) {
			e.printStackTrace();
		}

		/**
		 * To check the values of the actual location object
		 */
//        System.out.println(Location.getInstance().getLatitude()+" UND "+Location.getInstance().getLongitude());
		
		// Switch to OpenStreetMapActivity with the new GEO data saved in the location object, which is singleton.
		Intent i = new Intent(this, OpenStreetMapActivity.class);
		startActivity(i);
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case R.id.itemSettings:
    		startActivity(new Intent(this, SettingsActivity.class));
    		break;
    	case R.id.itemAddToilet:
    		startActivity(new Intent(this, AddToiletActivity.class));
    	break;
    	}
    	
    	return true;
    }
}